import React, {Component} from 'react'
import {
    Text,
    View,
    StyleSheet,
    Button,
    Image,
    FlatList,
    ScrollView,
    StyleProp,
    ViewStyle,
    TouchableOpacity, TextStyle
} from 'react-native'
import styles, {border, rectWithSize} from "../../style";

interface StepperProps {
    count: number,
    maxCount?: number,
    style?: StyleProp<ViewStyle>,
    textStyle?: TextStyle,
    countContainerStyle?: StyleProp<ViewStyle>,
    updateCount?: (count: number) => void
}

interface StepperState {
    count: number,
}

export default class Stepper extends Component<StepperProps, StepperState> {

    state = {
        count: 0
    };

    constructor(props: StepperProps) {
        super(props);
        this.state = {
            count: props.count,
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps !== this.props) {
            this.setState({
                count: nextProps.count
            })
        }
    }

    plus = () => {
        const count = this.state.count + 1;
        if (count > this.props.maxCount) return;
        this.setState({count});
        this.props.updateCount && this.props.updateCount(count);
    };

    reduce = () => {
        let count = this.state.count - 1;
        count = count < 1 ? 1 : count;
        this.setState({count});
        this.props.updateCount && this.props.updateCount(count);
    };

    getCount() {
        return this.state.count;
    }

    render() {
        const {style, countContainerStyle, textStyle} = this.props;
        const {count} = this.state;
        return (
            <View style={[StepperStyles.container, style]}>
                <View style={[border(1, "#DDDDDD"), rectWithSize(30), StepperStyles.border]}>
                    <TouchableOpacity onPress={this.reduce} style={[styles.flex, styles.centered]}>
                        <Text style={{fontSize: 14, color: "#999999"}}>-</Text>
                    </TouchableOpacity>
                </View>
                <View
                    style={[styles.centered, border(1, "#DDDDDD"), rectWithSize(30), StepperStyles.border, countContainerStyle]}><Text
                    style={[{fontSize: 14, color: "#000"}, textStyle]}>{count}</Text></View>
                <View style={[border(1, "#DDDDDD"), rectWithSize(30)]}>
                    <TouchableOpacity onPress={this.plus} style={[styles.flex, styles.centered]}>
                        <Text style={{fontSize: 14, color: "#629C36"}}>+</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}


const StepperStyles = StyleSheet.create({
    container: {
        flexDirection: "row"
    },
    border: {
        borderRightWidth: 0
    }
});
